<template>
  <div class="page-container user-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="page-header__content">
        <h1 class="page-title">用户管理</h1>
        <p class="page-description">管理系统用户和权限</p>
      </div>
      <div class="page-header__actions">
        <el-button
          type="primary"
          :icon="Plus"
          @click="showCreateDialog"
        >
          新增用户
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <div class="stat-card">
        <div class="stat-card__icon bg-purple">
          <el-icon>
            <UserIcon/>
          </el-icon>
        </div>
        <div class="stat-card__content">
          <div class="stat-card__value">{{ userStats.totalUsers }}</div>
          <div class="stat-card__title">总用户数</div>
          <div class="stat-card__desc">系统注册用户总数</div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-card__icon bg-green">
          <el-icon><CircleCheckFilled /></el-icon>
        </div>
        <div class="stat-card__content">
          <div class="stat-card__value">{{ userStats.activeUsers }}</div>
          <div class="stat-card__title">活跃用户</div>
          <div class="stat-card__desc">启用状态的用户</div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-card__icon bg-orange">
          <el-icon><Lock /></el-icon>
        </div>
        <div class="stat-card__content">
          <div class="stat-card__value">{{ userStats.disabledUsers }}</div>
          <div class="stat-card__title">禁用/锁定</div>
          <div class="stat-card__desc">禁用或锁定的用户</div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-card__icon bg-blue">
          <el-icon><UserFilled /></el-icon>
        </div>
        <div class="stat-card__content">
          <div class="stat-card__value">{{ userStats.adminUsers }}</div>
          <div class="stat-card__title">管理员</div>
          <div class="stat-card__desc">拥有管理权限的用户</div>
        </div>
      </div>
    </div>

    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form
        :model="searchForm"
        inline
        class="search-form__content"
      >
        <el-form-item label="用户名">
          <el-input
            v-model="searchForm.username"
            placeholder="请输入用户名"
            clearable
            class="input--medium"
          />
        </el-form-item>

        <el-form-item label="显示名称">
          <el-input
            v-model="searchForm.displayName"
            placeholder="请输入显示名称"
            clearable
            class="input--medium"
          />
        </el-form-item>

        <el-form-item>
          <template #label>
            <span class="flex--start">
              用户类型
              <el-tooltip content="超级管理员：拥有所有权限；管理员：管理用户和产品；开发者：可操作元数据；查看者：只读权限" placement="top">
                <el-icon style="color: var(--dbu-gray-500); cursor: help;" :size="16">
                  <QuestionFilled />
                </el-icon>
              </el-tooltip>
            </span>
          </template>
          <el-select
            v-model="searchForm.userType"
            placeholder="请选择用户类型"
            clearable
            class="input--small"
          >
            <el-option
              v-for="item in userTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            class="input--small"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="data-table">
      <BaseTable
        :data="tableData"
        :loading="loading"
        stripe
        border
        :pagination="true"
        :total="pagination.total"
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
        <el-table-column prop="username" label="用户名" width="120">
          <template #default="{ row }">
            <span class="flex--start">
              {{ row.username }}
              <el-tag v-if="isCurrentUser(row)" type="success" size="small" effect="light">当前用户</el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="displayName" label="显示名称" width="150" />
        <el-table-column prop="email" label="邮箱" min-width="200" />
        <el-table-column prop="userType" label="用户类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getUserTypeTagType(row.userType)">
              {{ getUserTypeLabel(row.userType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginTime" label="最后登录" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.lastLoginTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="warning"
              @click="handleResetPassword(row)"
              :disabled="isCurrentUser(row)"
            >
              重置密码
            </el-button>
            <el-dropdown
              v-if="hasMoreActions(row)"
              @command="(command: string) => handleDropdownCommand(command, row)"
            >
              <el-button size="small">
                更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    command="toggle"
                    v-if="(row.status === 'ENABLED' || row.status === 'DISABLED') && canToggleUserStatus(row)"
                  >
                    {{ row.status === 'ENABLED' ? '禁用' : '启用' }}
                  </el-dropdown-item>
                  <el-dropdown-item
                    command="lock"
                    v-if="row.status === 'ENABLED' && canLockUser(row)"
                  >
                    锁定
                  </el-dropdown-item>
                  <el-dropdown-item
                    command="unlock"
                    v-if="row.status === 'LOCKED' && canUnlockUser(row)"
                  >
                    {{ isCurrentUser(row) ? '解锁自己' : '解锁' }}
                  </el-dropdown-item>
                  <el-dropdown-item
                    command="delete"
                    divided
                    v-if="canDeleteUser(row)"
                  >
                    <span class="text-danger">删除</span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </BaseTable>
    </div>

    <!-- 创建/编辑用户对话框 -->
    <BaseDialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <BaseForm
        ref="userFormRef"
        v-model="userForm"
        :rules="userFormRules"
        :loading="submitLoading"
        @submit="handleSubmit"
        @reset="dialogVisible = false"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="userForm.username"
            :disabled="isEdit"
            placeholder="请输入用户名"
          />
        </el-form-item>

        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input
            v-model="userForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="显示名称" prop="displayName">
          <el-input
            v-model="userForm.displayName"
            placeholder="请输入显示名称"
          />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="userForm.email"
            placeholder="请输入邮箱"
          />
        </el-form-item>

        <el-form-item prop="userType">
          <template #label>
            <span class="flex--start">
              用户类型
              <el-tooltip content="超级管理员：拥有所有权限；管理员：管理用户和产品；开发者：可操作元数据；查看者：只读权限" placement="top">
                <el-icon style="color: var(--dbu-gray-500); cursor: help;" :size="16">
                  <QuestionFilled />
                </el-icon>
              </el-tooltip>
            </span>
          </template>
          <div class="width--full">
            <el-select
              v-model="userForm.userType"
              placeholder="请选择用户类型"
              class="input--full"
              :disabled="isEdit && userForm.userType === 'SUPER_ADMIN'"
            >
              <el-option
                v-for="item in userTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <div v-if="userForm.userType" class="padding--small margin-top--small">
              {{ getUserTypeDescription(userForm.userType) }}
            </div>
          </div>
        </el-form-item>

        <el-form-item label="状态" prop="status" v-if="isEdit">
          <el-select
            v-model="userForm.status"
            placeholder="请选择状态"
            class="input--full"
            :disabled="isCurrentUser({ id: userForm.id } as User)"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="isCurrentUser({ id: userForm.id } as User) && (item.value === UserStatus.DISABLED || item.value === UserStatus.LOCKED)"
            />
          </el-select>
          <div v-if="isCurrentUser({ id: userForm.id } as User)" class="warning-message">
            <el-icon style="margin-right: 4px;"><WarningFilled /></el-icon>
            不能将自己设置为禁用或锁定状态
          </div>
        </el-form-item>

        <template #actions>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            :loading="submitLoading"
            @click="handleSubmit"
          >
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </template>
      </BaseForm>
    </BaseDialog>
  </div>
</template>

<script setup lang="ts">
import {computed, onMounted, reactive, ref} from 'vue'
import {ElMessageBox, type FormInstance, type FormRules} from 'element-plus'
import {MessageService} from '@/utils/message'
import BaseTable from '@/components/common/tables/BaseTable.vue'
import BaseDialog from '@/components/common/dialogs/BaseDialog.vue'
import BaseForm from '@/components/common/forms/BaseForm.vue'
import {ArrowDown, CircleCheckFilled, Lock, Plus, QuestionFilled, Refresh, Search, User as UserIcon, UserFilled, WarningFilled} from '@element-plus/icons-vue'
import {authService} from '@/services/authService'
import {userService} from '@/services/userService'
import {useAuthStore} from '@/stores/auth'
import {formatDateTime} from '@/utils/date'
import type {CreateUserRequest, UpdateUserRequest, User, UserSearchParams} from '@/types/business/auth'
import {UserStatus, UserType} from '@/types/business/auth'

const authStore = useAuthStore()

// 响应式数据
const loading = ref(false)
const tableData = ref<User[]>([])
const dialogVisible = ref(false)
const submitLoading = ref(false)
const isEdit = ref(false)

// 用户统计数据
const userStats = reactive({
  totalUsers: 0,
  activeUsers: 0,
  disabledUsers: 0,
  adminUsers: 0
})

// 搜索表单
const searchForm = reactive<UserSearchParams>({
  username: '',
  displayName: '',
  userType: undefined,
  status: undefined,
  page: 0,
  size: 10,
  sort: 'createTime',
  direction: 'desc'
})

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 用户表单
const userForm = reactive<CreateUserRequest & UpdateUserRequest & { id?: number }>({
  username: '',
  password: '',
  displayName: '',
  email: '',
  userType: UserType.VIEWER,
  status: UserStatus.ENABLED,
  id: undefined
})

// 表单引用
const userFormRef = ref<FormInstance>()

// 计算属性
const dialogTitle = computed(() => isEdit.value ? '编辑用户' : '新增用户')

// 用户类型选项
const userTypeOptions = [
  { label: '超级管理员', value: UserType.SUPER_ADMIN },
  { label: '管理员', value: UserType.ADMIN },
  { label: '开发者', value: UserType.DEVELOPER },
  { label: '查看者', value: UserType.VIEWER }
]

// 状态选项
const statusOptions = [
  { label: '启用', value: UserStatus.ENABLED },
  { label: '禁用', value: UserStatus.DISABLED },
  { label: '锁定', value: UserStatus.LOCKED }
]

// 表单验证规则
const userFormRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 50, message: '用户名长度在 3 到 50 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于 6 位', trigger: 'blur' }
  ],
  displayName: [
    { required: true, message: '请输入显示名称', trigger: 'blur' },
    { max: 100, message: '显示名称不能超过 100 个字符', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  userType: [
    { required: true, message: '请选择用户类型', trigger: 'change' }
  ]
}

// 方法定义
const fetchData = async () => {
  try {
    loading.value = true
    const params = {
      ...searchForm,
      page: pagination.current - 1
    }
    const response = await authService.getUsers(params)
    tableData.value = response.data!.content
    pagination.total = response.data!.totalElements

    // 计算统计数据
    updateUserStats(response.data!.content)
  } catch (error) {
    MessageService.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 更新用户统计数据
const updateUserStats = (users: User[]) => {
  userStats.totalUsers = pagination.total
  userStats.activeUsers = users.filter(user => user.status === 'ENABLED').length
  userStats.disabledUsers = users.filter(user => user.status === 'DISABLED' || user.status === 'LOCKED').length
  userStats.adminUsers = users.filter(user => user.userType === 'SUPER_ADMIN' || user.userType === 'ADMIN').length
}

// 获取全部用户统计数据
const fetchAllUserStats = async () => {
  try {
    const response = await authService.getUsers({ page: 0, size: 1000 })
    if (response.data?.content) {
      updateUserStats(response.data.content)
    }
  } catch (error) {
    console.error('获取用户统计数据失败:', error)
  }
}

const handleSearch = () => {
  pagination.current = 1
  fetchData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    username: '',
    displayName: '',
    userType: undefined,
    status: undefined
  })
  handleSearch()
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  fetchData()
}

const handleCurrentChange = (current: number) => {
  pagination.current = current
  fetchData()
}

const showCreateDialog = () => {
  isEdit.value = false
  dialogVisible.value = true
  resetForm()
}

const handleEdit = (row: User) => {
  isEdit.value = true
  dialogVisible.value = true
  Object.assign(userForm, {
    ...row,
    password: '' // 编辑时不显示密码
  })
}

const handleSubmit = async () => {
  if (!userFormRef.value) return

  try {
    await userFormRef.value.validate()
    submitLoading.value = true

    if (isEdit.value) {
      const updateData: UpdateUserRequest = {
        displayName: userForm.displayName,
        email: userForm.email,
        userType: userForm.userType,
        status: userForm.status
      }
      await userService.updateUser(userForm.id!, updateData)
    } else {
      const createData: CreateUserRequest = {
        username: userForm.username!,
        password: userForm.password!,
        displayName: userForm.displayName!,
        email: userForm.email,
        userType: userForm.userType!
      }
      await userService.createUser(createData)
    }

    dialogVisible.value = false
    fetchData()
  } catch (error: any) {
    const message = error.response?.data?.message || '操作失败'
    MessageService.error(message)
  } finally {
    submitLoading.value = false
  }
}

const handleResetPassword = async (row: User) => {
  try {
    // 检查是否在操作自己
    if (isCurrentUser(row)) {
      MessageService.warning('不能重置自己的密码')
      return
    }

    await ElMessageBox.confirm(
      `确定要重置用户 "${row.displayName}" 的密码吗？`,
      '重置密码',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await userService.resetPassword(row.id)
    const tempPassword = response.data
    await ElMessageBox.alert(
      `临时密码：${tempPassword}\n请妥善保管并通知用户及时修改密码`,
      '密码重置成功',
      {
        confirmButtonText: '确定',
        type: 'success'
      }
    )
  } catch (error: any) {
    if (error !== 'cancel') {
      const message = error.response?.data?.message || '重置密码失败'
      MessageService.error(message)
    }
  }
}

const handleDropdownCommand = async (command: string, row: User) => {
  try {
    switch (command) {
      case 'toggle':
        await userService.toggleUserStatus(row.id)
        break
      case 'lock':
        await userService.lockUser(row.id)
        break
      case 'unlock':
        await userService.unlockUser(row.id)
        break
      case 'delete':
        await handleDelete(row)
        break
    }
    fetchData()
  } catch (error: any) {
    const message = error.response?.data?.message || '操作失败'
    MessageService.error(message)
  }
}

const handleDelete = async (row: User) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${row.displayName}" 吗？此操作不可恢复！`,
      '删除用户',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'error'
      }
    )

    await userService.deleteUser(row.id)
  } catch (error) {
    if (error !== 'cancel') {
      throw error
    }
  }
}

const resetForm = () => {
  Object.assign(userForm, {
    id: undefined,
    username: '',
    password: '',
    displayName: '',
    email: '',
    userType: UserType.VIEWER,
    status: UserStatus.ENABLED
  })
  userFormRef.value?.resetFields()
}

// 工具方法
const getUserTypeLabel = (userType: UserType) => {
  const option = userTypeOptions.find(item => item.value === userType)
  return option?.label || userType
}

const getUserTypeDescription = (userType: UserType) => {
  const descMap = {
    'SUPER_ADMIN': '拥有系统所有权限，包括用户管理、系统配置、数据库元数据管理等。建议只分配给少数核心管理员。',
    'ADMIN': '拥有用户管理、产品管理权限，可以管理用户账户和产品授权，查看所有元数据。建议分配给项目管理员。',
    'DEVELOPER': '可以创建和编辑数据库元数据（如表、列、索引等），但不能管理用户。建议分配给开发人员和DBA。',
    'VIEWER': '只能查看数据库元数据，不能进行任何编辑操作。建议分配给需要查看数据结构的人员。'
  }
  return descMap[userType] || ''
}

const getUserTypeTagType = (userType: UserType) => {
  const typeMap = {
    'SUPER_ADMIN': 'danger',
    'ADMIN': 'warning',
    'DEVELOPER': 'primary',
    'VIEWER': 'info'
  }
  return typeMap[userType] || 'info'
}

const getStatusLabel = (status: UserStatus) => {
  const option = statusOptions.find(item => item.value === status)
  return option?.label || status
}

const getStatusTagType = (status: UserStatus) => {
  const typeMap = {
    'ENABLED': 'success',
    'DISABLED': 'info',
    'LOCKED': 'danger'
  }
  return typeMap[status] || 'info'
}


const canDeleteUser = (row: User) => {
  // 不能删除自己
  if (row.id === authStore.currentUser?.id) return false
  // 只有超级管理员可以删除超级管理员
  if (row.userType === UserType.SUPER_ADMIN && !authStore.isSuperAdmin) return false
  return true
}

const canToggleUserStatus = (row: User) => {
  // 不能禁用或启用自己
  if (row.id === authStore.currentUser?.id) return false
  return true
}

const canLockUser = (row: User) => {
  // 不能锁定自己
  if (row.id === authStore.currentUser?.id) return false
  return true
}

const canUnlockUser = (row: User) => {
  // 可以解锁自己（如果自己被锁定了）
  return true
}

const isCurrentUser = (row: User) => {
  return row.id === authStore.currentUser?.id
}

const hasMoreActions = (row: User) => {
  return (
    (row.status === 'ENABLED' || row.status === 'DISABLED') && canToggleUserStatus(row) ||
    (row.status === 'ENABLED' && canLockUser(row)) ||
    (row.status === 'LOCKED' && canUnlockUser(row)) ||
    canDeleteUser(row)
  )
}

// 生命周期
onMounted(async () => {
  await fetchData()
  // 获取全局统计数据（基于当前页面数据）
  fetchAllUserStats()
})
</script>

<style scoped>
/* 用户管理页面特有样式 */
.text-danger {
  color: var(--dbu-error);
}

.warning-message {
  padding: var(--dbu-space-2) var(--dbu-space-3);
  background: var(--dbu-warning-bg);
  border-radius: var(--dbu-radius);
  font-size: var(--dbu-text-sm);
  color: var(--dbu-warning);
  margin-top: var(--dbu-space-2);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: stretch;
  }

  .page-header__actions {
    margin-left: 0;
    margin-top: var(--dbu-space-4);
  }

  .search-form__content {
    display: block;
  }

  .search-form__content .el-form-item {
    display: block;
    margin-bottom: var(--dbu-space-4);
  }

  .search-form__content .el-form-item__label {
    display: block;
    margin-bottom: var(--dbu-space-2);
  }
}
</style>